﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Net.Mail;
//using System.Web.Mail;

namespace XmlToPdf
{
    public class Progress
    {
        //当前数据集
        private List<Salary> dataList = new List<Salary> { };
        //文件路径
        private const string filePath = "../server/XmlToPdf/";
        //文件名
        private string xmlName = "result";
        //公司内部密码，如：sysg2009
        private string companyPassword = "sysg";

        

        /// <summary>
        /// 接受客户端数据
        /// </summary>
        /// <param name="strAll">xml中的数据</param>
        /// <param name="salaryDate">当前年月</param>
        public bool Receive(string strAll, string salaryDate)
        {
            try
            {
                //CreatePdf.Create(strAll, salaryDate);
                //公司内部密码，如：sysg2009
                companyPassword += salaryDate.Substring(0, 4);

                //把包含所有员工的string分割，其结果是每个员工对应一个string
                List<string> list = splitString(strAll);
                
                foreach (string strSingle in list)
                {                    
                    //利用每个员工的信息（string），生成pdf文件
                    progress(strSingle, salaryDate);
                } 
            }
            catch (Exception e)
            {
                return false;
            }            

            return true;
            
        }

        /// <summary>
        /// 把包含所有员工的string分割，
        /// 其结果是每个员工对应一个string
        /// </summary>
        /// <param name="strAll">所有员工的信息</param>
        /// <returns></returns>
        private List<string> splitString(string strAll)
        {
            //分隔符,"\r\n"
            string[] sep = new string[] { System.Environment.NewLine };
            //执行分割
            string[] strResult = strAll.Split(sep, StringSplitOptions.None);
            //
            List<string> lst = new List<string>();
            //
            StringBuilder sb = new StringBuilder();
            //添加第一行 <?xml version="1.0" encoding="utf-8" ?>
            sb.AppendLine(strResult[0]);
            //添加第2行 <salaries year="2009" month="3">
            sb.AppendLine(strResult[1]);
            for (int i = 2; i < strResult.Length; i++)
            {
                switch (strResult[i].Trim())
                {
                        
                    case "</salary>":
                        //添加结束符</salary>
                        sb.AppendLine(strResult[i]);
                        //添加结束符</salaries>
                        sb.AppendLine("</salaries>");
                        //一个员工结束，添加至lst
                        lst.Add(sb.ToString());
                        //开始新的一个员工
                        sb = new StringBuilder();
                        //添加第一行 <?xml version="1.0" encoding="utf-8" ?>
                        sb.AppendLine(strResult[0]);
                        //添加第2行 <salaries year="2009" month="3">
                        sb.AppendLine(strResult[1]);
                        break;
                    case "</salaries>":
                        //全部结束
                        break;
                    default:
                        //添加
                        sb.AppendLine(strResult[i]);
                        break;
                }
                
            }
            
            return lst;
        }

        /// <summary>
        /// 利用每个员工的信息(strSingle)
        /// 生成pdf文件,并给每个人发信
        /// </summary>
        /// <param name="strSingle">每个员工的信息</param>
        /// <param name="salaryDate">当前年月</param>
        private void progress(string strSingle, string salaryDate)
        {
            //<email>在strSingle中的开始位置
            int emailstartIndex = strSingle.IndexOf("<email>");
            //</email>在strSingle中的开始位置
            int emailendIndex = strSingle.IndexOf("</email>");
            //取得email地址
            string emailAddress = strSingle.Substring(emailstartIndex, emailendIndex - emailstartIndex).Replace("<email>", "");
            //xmlName = emailAddress.Replace("@sysystem.com.cn","");
            xmlName = emailAddress;

            //把string转化为XmlReader
            XmlReader reader = XmlReader.Create(new StringReader(strSingle));

            //利用xslt，把XmlReader转化为iTextSharp能够识别的xml格式
            FormatXml.FormatXmlReader(reader, filePath, xmlName, salaryDate);            

            //利用格式化之后的xml生成pdf文件
            XmlToPdf.ToPdf(filePath, xmlName, companyPassword);

            //发送邮件
            sendMail(emailAddress);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="emailAddress"></param>
        private void sendMail(string emailAddress)
        {
            //消息对象
            MailMessage message = new MailMessage();
            //邮件发送者
            message.From = new MailAddress("he.ziyan@sysystem.com.cn");
            //message.To.Add(new MailAddress(emailAddress));
            //邮件接收人
            message.To.Add(new MailAddress("he.ziyan@sysystem.com.cn"));
            //邮件cc对象
            message.CC.Add(new MailAddress("he.ziyan@sysystem.com.cn"));
            //邮件主题
            message.Subject = "Salary";
            //邮件内容
            message.Body = "This is your Salary";

            //创建附件 
            Attachment attachment = new Attachment(filePath + xmlName);
            //添加附件 
            message.Attachments.Add(attachment); 

            //客户端对象
            SmtpClient client = new SmtpClient("127.0.0.1", 25);
            //发送
            client.Send(message);
            //SmtpMail.SmtpServer = "localhost"

            //// Command line argument must the the SMTP host.
            //SmtpClient client = new SmtpClient("127.0.0.1");
            //// Specify the e-mail sender.
            //// Create a mailing address that includes a UTF8 character
            //// in the display name.
            //MailAddress from = new MailAddress("he.ziyan@sysystem.com.cn",
            //   "heziyan",
            //System.Text.Encoding.UTF8);
            //// Set destinations for the e-mail message.
            //MailAddress to = new MailAddress("he.ziyan@sysystem.com.cn");
            //// Specify the message content.
            //MailMessage message = new MailMessage(from, to);
            //message.Body = "This is a test e-mail message sent by an application. ";
            //// Include some non-ASCII characters in body and subject.
            //string someArrows = new string(new char[] { '\u2190', '\u2191', '\u2192', '\u2193' });
            //message.Body += Environment.NewLine + someArrows;
            //message.BodyEncoding = System.Text.Encoding.UTF8;
            //message.Subject = "test message 1" + someArrows;
            //message.SubjectEncoding = System.Text.Encoding.UTF8;
            //// Set the method that is called back when the send operation ends.
            ////client.SendCompleted += new
            ////SendCompletedEventHandler(SendCompletedCallback);
            //// The userState can be any object that allows your callback 
            //// method to identify this send operation.
            //// For this example, the userToken is a string constant.
            //string userState = "test message1";
            //client.SendAsync(message, userState);
            //Console.WriteLine("Sending message... press c to cancel mail. Press any other key to exit.");
            //string answer = Console.ReadLine();
            //// If the user canceled the send, and mail hasn't been sent yet,
            //// then cancel the pending operation.
            ////if (answer.StartsWith("c") && mailSent == false)
            ////{
            //    client.SendAsyncCancel();
            ////}
            //// Clean up.
            //message.Dispose();
            //Console.WriteLine("Goodbye.");

        }

        #region 未使用

        public void Receive(List<Salary> lst)
        {

        }

        public static void Main()
        {

        } 
        #endregion

    }
}
